package org.ehais.ws;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket的服务端
 */
@Component
@Slf4j
@ServerEndpoint("/WsServer") //  /{sessionId}
public class WSServer {
	
	private static int onLineCount = 0;//记录在线连接数，应该做成线程安全的

    public static ConcurrentHashMap<String, WSServer> webSocketMap = new ConcurrentHashMap<String, WSServer>();
    
    private static CopyOnWriteArraySet<WSServer> myWebSockets = new CopyOnWriteArraySet<WSServer>();

    /**
     * 与客户端连接的session
     */
    private Session session;

    /**
     * 客户端id
     */
//    private String sessionId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) { //  , @PathParam("sessionId") String sessionId
//        this.sessionId = sessionId;
        this.session = session;
        myWebSockets.add(this);
//        if (webSocketMap.containsKey(sessionId)) {
//            webSocketMap.remove(sessionId);
//
//            webSocketMap.put(sessionId, this);
//        } else {
//
//            webSocketMap.put(sessionId, this);
//        }

        log.info("客户端:" + session.getId() + ",连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
//        if (webSocketMap.containsKey(sessionId)) {
//            webSocketMap.remove(sessionId);
//        }
        myWebSockets.remove(this);
        subOnlineCount();
//        log.info("客户端:" + sessionId + ",断开连接");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + session.getId() + ",报文:" + message);

//        sendMessage(message);
        
        for (WSServer socket : myWebSockets) {
        	if(socket.session.getId().equals(session.getId())) {
        		try {
                    socket.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
        	}
            
        }
	
    }


    /**
     * @param session
     * @param e
     */
    @OnError
    public void onError(Session session, Throwable e) {
        log.error("连接错误:" + session.getId(), e);
    }


    public void sendMessage(String message) {
        try {
//	        this.session.getAsyncRemote().sendText(message);
	        this.session.getBasicRemote().sendText(message);
        } catch (Exception e) {
//            log.error("发送客户端:" + sessionId + ",异常", e);
        }
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, String id) {
        log.info("发送给客户端:" + id + ",报文:" + message);
        if (StringUtils.isNotBlank(id) && webSocketMap.containsKey(id)) {
            webSocketMap.get(id).sendMessage(message);
        } else {
            log.error("客户端:" + id + ",不在线");
        }
    }
    
    
    public static synchronized void addOnlineCount() {
    	WSServer.onLineCount++;
    }

    public static synchronized void subOnlineCount() {
    	WSServer.onLineCount--;
    }

    public static synchronized int getOnLineCount() {
        return onLineCount;
    }
	

}
